<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>受控组件</title>
  </head>
  <body>
    <div id="test"></div>
    <!-- 引入react核心库  优先 -->
    <script type="text/javascript" src="../js/react.development.js"></script>
    <!-- 引入react-dom用于支持react操作DOM，依赖react核心库 -->
    <script
      type="text/javascript"
      src="../js/react-dom.development.js"
    ></script>
    <!-- 引入babel，用于将jsx转换为js -->
    <script type="text/javascript" src="../js//babel.min.js"></script>
    <script type="text/babel">
      //    这节课学到一个卸载组件和三个生命周期函数 ：
      // 卸载组件：
      //   React.unmountComponentAtNode(document.getElementById("test"));
      // 生命周期函数：
      //  1.render(){} 挂载（渲染）组件
      // 2. componentDidmount(){} 组件挂载完成
      // 3.componentWillUnmount(){} 组件卸载之前
      //

      class Demo extends React.Component {
        timer = null;
        state = { opacity: 1 };
        death = () => {
          // 卸载组件   unmountComponentAtNode
          ReactDOM.unmountComponentAtNode(document.getElementById("test"));
        };

        //组件卸载之前
        componentWillUnmount() {
          clearInterval(this.timer);
        }
        //组件挂载完毕
        componentDidMount() {
          console.log("组件挂载完毕");
          this.timer = setInterval(() => {
            let opacity = this.state.opacity;
            opacity -= 0.1;
            if (opacity <= 0) opacity = 1;
            this.setState({ opacity });
          }, 200);
        }
        render() {
          //挂载组件
          return (
            <div>
              <h2 style={{ opacity: this.state.opacity }}>学不会怎么办</h2>
              <button onClick={this.death}>点击</button>
            </div>
          );
        }
      }
      ReactDOM.render(<Demo />, document.getElementById("test"));
    </script>
  </body>
</html>
